package com.qboot.core.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.qboot.common.consts.NumberConst;
import com.qboot.common.entity.BaseEntity;
import com.qboot.common.utils.SaTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * 公共字段填充
 *
 * @author Tellsea
 * @date 2022/11/26
 */
@Slf4j
@Component
public class PublicFieldMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter(BaseEntity.Fields.createBy) && ObjectUtils.isEmpty(metaObject.getValue(BaseEntity.Fields.createBy))) {
            this.setFieldValByName(BaseEntity.Fields.createBy, SaTokenUtils.getUser().getUserName(), metaObject);
        }
        if (metaObject.hasGetter(BaseEntity.Fields.createTime) && ObjectUtils.isEmpty(metaObject.getValue(BaseEntity.Fields.createTime))) {
            this.setFieldValByName(BaseEntity.Fields.createTime, new Date(), metaObject);
        }
        if (metaObject.hasGetter(BaseEntity.deleteStatus) && ObjectUtils.isEmpty(metaObject.getValue(BaseEntity.deleteStatus))) {
            this.setFieldValByName(BaseEntity.deleteStatus, NumberConst.ONE, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter(BaseEntity.Fields.updateBy) && ObjectUtils.isEmpty(metaObject.getValue(BaseEntity.Fields.updateBy))) {
            this.setFieldValByName(BaseEntity.Fields.updateBy, SaTokenUtils.getUser().getUserName(), metaObject);
        }
        if (metaObject.hasGetter(BaseEntity.Fields.updateTime) && ObjectUtils.isEmpty(metaObject.getValue(BaseEntity.Fields.updateTime))) {
            this.setFieldValByName(BaseEntity.Fields.updateTime, new Date(), metaObject);
        }
    }
}
